package com.rpay.common.util.common;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public final class CommonUtils {

    public static boolean isNotEmpty(Object o) {
        return !isEmpty(o);
    }


    public static boolean isEmpty(Object value) {
        if (value == null) return true;

        if (value instanceof String) return (((String) value).trim()).length() == 0;
        if (value instanceof Object[]) return ((Object[]) value).length == 0;
        if (value instanceof Collection) return ((Collection<? extends Object>) value).size() == 0;
        if (value instanceof Map) return ((Map<? extends Object, ? extends Object>) value).size() == 0;
        if (value instanceof CharSequence) return ((CharSequence) value).length() == 0;

        // These types would flood the log
        // Number covers: BigDecimal, BigInteger, Byte, Double, Float, Integer,
        // Long, Short
        if (value instanceof Boolean) return false;
        if (value instanceof Number) return false;
        if (value instanceof Character) return false;
        if (value instanceof Date) return false;

        return false;
    }


    public static boolean isChinaMobileNo(String mobile) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(18[0-9])|(17[0-9])|(14[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    public static boolean isNumber(String input) {
        char[] chars = input.toCharArray();
        for (char c : chars) {
            if (!Character.isDigit(c)) return false;
        }
        return true;
    }

    public static boolean isEmpty(String input) {
        return input == null || input.trim().length() == 0;
    }

    /**
     * 去除字符串中所包含的空格（包括:空格(全角，半角)、制表符、换页符等）
     *
     * @param str 待去除空格的字符串
     * @return
     */
    public static String removeAllBlank(String str) {
        String result = "";
        if (!isEmpty(str)) {
            result = str.replaceAll("[　*| *| *|\\s*]*", "");
        }
        return result;
    }

    public static String md5(String input) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());

            byte byteData[] = md.digest();

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                String hex = Integer.toHexString(0xff & byteData[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

    }

    public static String genUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().toLowerCase();
    }

    public static void randomList(List<?> list) {
        Collections.sort(list, new Comparator() {
            HashMap map = new HashMap();

            public int compare(Object v1, Object v2) {
                init(v1);
                init(v2);

                double n1 = ((Double) map.get(v1)).doubleValue();
                double n2 = ((Double) map.get(v2)).doubleValue();
                if (n1 > n2)
                    return 1;
                else if (n1 < n2)
                    return -1;
                return 0;
            }

            private void init(Object v) {
                if (map.get(v) == null) {
                    map.put(v, new Double(Math.random()));
                }
            }

            protected void finalize() throws Throwable {
                map = null;
            }
        });
    }

    public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;

    }

    public static String getRandDateNum(int charCount, int maxLength) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        Calendar calendar = Calendar.getInstance();
        int minutes = calendar.get(Calendar.MINUTE);    // 分
        String minute = minutes < 10 ? "0" + minutes : String.valueOf(minutes);
        int seconds = calendar.get(Calendar.SECOND);    // 秒
        String second = seconds < 10 ? "0" + seconds : String.valueOf(seconds);
        charValue += minute + second;
        if (charValue.length() > maxLength) {
            charValue = charValue.substring(0, maxLength);
        }
        return charValue;

    }

    public static int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }

    /**
     * 格式化double数据
     *
     * @param d   要格式化的数据
     * @param num 小数位数
     * @return
     */
    public static double formatDouble(double d, int num) {
        String zero = "";
        for (int i = 0; i < num; i++) {
            zero += "0";
        }
        DecimalFormat df = new DecimalFormat("#." + zero);
        return Double.parseDouble(df.format(d));
    }

    /**
     * 格式化double数据
     *
     * @param d 要格式化的数据
     * @return 格式化后的数据，小数点后为0则返回整数，如：d=600.0，返回600
     */
    public static String formatDouble(double d) {
        DecimalFormat sDecimalFormat = new DecimalFormat("#.##");
        return sDecimalFormat.format(d);
    }

    public static Date buildExpirationDate() {
        Calendar calendar = Calendar.getInstance();
        //calendar.add(Calendar.MINUTE, 2);
//        calendar.add(Calendar.HOUR_OF_DAY, 24 * 30);
        calendar.add(Calendar.HOUR_OF_DAY, 24);
        return calendar.getTime();
    }

    public static boolean matchRegex(String value, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}
